package com.srpingde.hhh;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.springde.hhh.R;
import com.srpingde.hhh.application.HhhApp;
import com.srpingde.hhh.application.HHHDataManage;
import com.srpingde.hhh.bean.DingDanBean;
import com.srpingde.hhh.bean.DingDanBeanData;
import com.srpingde.hhh.http.AsyncHttpResponseHandler;
import com.srpingde.hhh.jiekou.HHHIml;
import com.srpingde.hhh.jiekou.HHHInterface;

public class DingDanActivity extends Activity {
	ImageView back;
	HHHIml weiQuIml;
	DingDanBean guangGao;
	DingDanAdapter adapter;
	ListView dingdan_lv;
	int totalAmount;
	private int shuLiang; 
	Button dingDandel;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ding_dan);
        shuLiang = 0;
        back = (ImageView) findViewById(R.id.about_back);
        weiQuIml = new HHHIml();
        dingdan_lv = (ListView) findViewById(R.id.dingdan_lv);
        dingDandel = (Button) findViewById(R.id.dingdan_del);
        adapter = new DingDanAdapter();
        layout();
        getData();
        dingdan_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent in = new Intent(DingDanActivity.this,DingDanDetailActivity.class);
				in.putExtra("id", arg2);
				startActivity(in);
			}
		});
        
        dingdan_lv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(DingDanActivity.this)
				.setTitle("提示").setMessage("确定要删除吗？")
				.setPositiveButton("确定",new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,int which) {
								// TODO Auto-generated method stub
								delete(guangGao.getRows().get(arg2).getOid());
								guangGao.getRows().remove(arg2);
								// // listView.setAdapter(adapter);
								 adapter.notifyDataSetChanged();
							}
						}).setNegativeButton("取消", null).create().show();
				return false;
			}
		});
        
        dingDandel.setOnClickListener(new Button.OnClickListener(){
        	
        	@Override
        	public void onClick(View v){
        		new AlertDialog.Builder(DingDanActivity.this)
				.setTitle("提示").setMessage("确定要清空吗？")
				.setPositiveButton("确定",new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,int which) {
								// TODO Auto-generated method stub
								for(int q = 0;q<dingdan_lv.getCount();q++)
								{
									delete2(guangGao.getRows().get(q).getOid());				 
								}
								guangGao.getRows().clear();
								Intent in = new Intent(DingDanActivity.this,DingDanActivity.class);			
								startActivity(in);		
								DingDanActivity.this.finish();
							}
						}).setNegativeButton("取消", null).create().show();
        	}	
        });  
    }
    /*
     * 下单后立即更新订单界面
     */
   @Override  
    protected void onResume() { 
   	getData();
       super.onResume();  
		//显示总额
		//Toast.makeText(DingDanActivity.this, String.valueOf(totalAmount), Toast.LENGTH_LONG).show();
   }  


    private void getData(){
    	String str = HHHInterface.httpHeader + "api.php?act=getorder&uid="+HhhApp.getInstance().getUid()+"&pagesize=10&page=1";
    	weiQuIml.yiJianFanKui(DingDanActivity.this, str,new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				Log.e("mytag",content+"=======分类的数据=");
				ObjectMapper mapper = new ObjectMapper();
				try {
					guangGao = mapper.readValue(content, DingDanBean.class);
					HHHDataManage.getInstance().setDingDanBean(guangGao);
					dingdan_lv.setAdapter(adapter);
					
					for(int i=0;i<3;i++){
						//累计总额
						totalAmount += Integer.valueOf(guangGao.getTotal());
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		});
    }
  //点击事件
  	public void onClick(View v){
  		switch (v.getId()) {
  		case R.id.about_back:
  			finish();
  			break;
  		}
  	}
    private void layout() {
		// 头的高度
		TextView top_title_tv = (TextView) findViewById(R.id.about_title);
		RelativeLayout.LayoutParams titleLayoutParams = (RelativeLayout.LayoutParams) top_title_tv.getLayoutParams();
		titleLayoutParams.height = HhhApp.getInstance().title_h();
		top_title_tv.setLayoutParams(titleLayoutParams);
		//返回按钮
		RelativeLayout.LayoutParams backLayoutParams = (LayoutParams) back.getLayoutParams();
		backLayoutParams.height = HhhApp.getInstance().title_h();
		back.setLayoutParams(backLayoutParams);
	}
    class DingDanAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return guangGao.getRows().size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			shuLiang = 0;
			String dsad = null;
			arg1 = LayoutInflater.from(DingDanActivity.this).inflate(R.layout.dingdan_item, null);
			ImageView imageView = (ImageView) arg1.findViewById(R.id.dingdan_iv);
			TextView dingdan_hao = (TextView) arg1.findViewById(R.id.dingdan_hao);
			TextView dingdan_time = (TextView) arg1.findViewById(R.id.dingdan_time);
			TextView  dingdan_show_num = (TextView) arg1.findViewById(R.id.dingdan_show_num);
			TextView dingdan_jine = (TextView) arg1.findViewById(R.id.dingdan_jine);
			String str;
			final ImageView kvShow = imageView;
			if(!guangGao.getRows().get(arg0).getDetail().toString().equals("[]")){
				dsad = guangGao.getRows().get(arg0).getDetail().get(0).getPurl();
			}
    		ImageLoader.getInstance().loadImage(HHHIml.httpHeader + dsad, new SimpleImageLoadingListener(){
    			@Override
    			public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {
    				BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
    				//kvShow.setImageBitmap(bitmap);
    				kvShow.setBackgroundDrawable(bitmapDrawable);
    			}
    		});
    		str = guangGao.getRows().get(arg0).getOrderno();
			dingdan_hao.setText("订单号: "+ str);
			//dingdan_time.setText("时间: "+guangGao.getRows().get(arg0).getOrderno().subSequence(0, 4));
			dingdan_time.setText("时间: "+ str.subSequence(0, 4) + "-" + str.subSequence(4, 6) + "-" + str.subSequence(6, 8) + "/" + str.subSequence(8, 10) + ":" + str.subSequence(10, 12));
			//dingdan_show_num.setText("数量: "+guangGao.getRows().get(arg0).getStatus());
			DingDanBeanData dingDanBean = guangGao.getRows().get(arg0);
	        for(DingDanDetailBean bean : dingDanBean.getDetail()){
	    		shuLiang += Integer.parseInt(bean.getAmount());
	    	}
	        dingdan_show_num.setText("数量: " + shuLiang);
			dingdan_jine.setText("订单总额: "+guangGao.getRows().get(arg0).getMoney());

			return arg1;
		}
    }
    
    public void delete(String oid) {
		String str = HHHInterface.httpHeader + "api.php?tab=order&act=del&oid="
				+ oid + "&uid=" + HhhApp.getInstance().getUid();
		Log.e("删除", "pid"+oid+"uid"+HhhApp.getInstance().getUid());
		weiQuIml.gouWuChedeleteHttp(str, DingDanActivity.this,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content + "================收藏返回的数据");
						try {
							JSONObject jsonObject = new JSONObject(content);
							if (jsonObject.getBoolean("return")) {
								//WeiQuApp.getInstance().showDialog(GouWuCheActivity.this, "删除成功");
								Intent intent = new Intent(DingDanActivity.this,DingDanActivity.class);
								startActivity(intent);
								DingDanActivity.this.finish();
							} else {
								HhhApp.getInstance().showDialog(DingDanActivity.this, "删除失败");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}
	
	public void delete2(String oid) {
		String str = HHHInterface.httpHeader + "api.php?tab=order&act=del&oid="
				+ oid + "&uid=" + HhhApp.getInstance().getUid();
		Log.e("删除", "pid"+oid+"uid"+HhhApp.getInstance().getUid());
		weiQuIml.gouWuChedeleteHttp(str, DingDanActivity.this,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content + "================收藏返回的数据");
						try {
							JSONObject jsonObject = new JSONObject(content);
							if (jsonObject.getBoolean("return")) {
								//WeiQuApp.getInstance().showDialog(GouWuCheActivity.this, "删除成功");
							} else {
								HhhApp.getInstance().showDialog(DingDanActivity.this, "删除失败");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}
}
